package submitter;

use Exporter;
use Socket;
use Util::Logger;

our @ISA = qw( Exporter );
our @EXPORT = qw( sumbit_flags );




$server_ip='194.226.244.122';
$server_port=31337;
$sender_sleep=2;

$our_team_num=4; #<<<<<<<<<<<<!!!!!!!!!!!!!!!<<<<<<<<<<<<<<!!!!!!!!!!!!!!!!!!!<<<<<<<<<<<<<!!!!!!!!!!!!!!!





$gl=new Util::Logger('submitter_log.txt');

%statuses=
    (
	'Sorry, is this a flag?'	=> 3,
#	'AAAAag?'	=> 3,
    );


sub new
{
    my ($self)=@_;
    my $obj={};
    bless $obj;
}

sub get_status
{
    my ($self,$ret_str,$flag)=@_;
    if (exists($statuses{$ret_str}))
    {
	return $statuses{$ret_str};
    }else
    {
	$gl->alert("Unknown status for '$ret_str', flag: '$flag'");
	return 0;
    }
    
}

sub submit_flags_err
{
    my ($error,$status,$length)=@_;
    my @ret;
    $gl->alert("SUBMITTER_WHILE_CONNECT: $error $status");
    push(@ret,$status) for (1..$length);
    return \@ret;
}

sub submit_flags
{
    local $\='';
    my ($self,$flags)=@_;

    my $sock;
    my $remote  = $server_ip;
    my $port    = $server_port;
    my $iaddr   = inet_aton($remote) or return submit_flags_err("no host: $remote",0,scalar @$flags);
    my $paddr   = sockaddr_in($port, $iaddr);

    my $proto   = getprotobyname('tcp');
    socket($sock, PF_INET, SOCK_STREAM, $proto)  or return submit_flags_err("socket: $!",0,scalar @$flags);
    connect($sock, $paddr) or return submit_flags_err("connect: $!",0,scalar @$flags);

    select $sock;
    $|++;
    select STDOUT;

    <$sock>;    
    print $sock "$our_team_num\r\n";
    <$sock>;
    $ret=[];

    for(@$flags)
    {
	my $a;
#	$s->print("$_\r\n");
	print "EvaL\n";
	eval
	{
	    if ((print $sock "$_\r\n")&&($a=<$sock>))
	    {
		$a=~s/[\r\n]+$//;
		print "Sent $_ Got $a\n";
		my $status=$self->get_status($a,$_);
		push(@$ret,$status);
		$gl->alert("Flag:$_;Got:$a;Status:$status");
		print "\n";
	    }else
	    {
		print "OOps $_\n";
		push(@$ret,0);
	    }
	};
	if($@)
	{
	    print "OOps eval $_\n";
            push(@$ret,0);
	}
	sleep($sender_sleep);
	print "Sleep $sender_sleep sec.\n";
    }
    print "END_FOR\n";
    shutdown($sock,2);
    return $ret;
}

1;

